package com.hb.trade.api.routine.controller.project.file;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.center.sys.entity.DistrictInfo;
import com.hb.core.pojo.enums.CommonTypeEnum;
import com.hb.core.pojo.enums.MemberTypeEnum;
import com.hb.core.pojo.project.evaluation.dto.EvaluationSummaryAddDTO;
import com.hb.core.pojo.project.evaluation.dto.EvaluationSummaryDTO;
import com.hb.core.pojo.project.evaluation.entity.EvaluationCommitteeMembers;
import com.hb.core.pojo.project.file.dto.*;
import com.hb.core.pojo.project.opening.dto.OpeningSetDTO;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.dto.BidSectionTenderDTO;
import com.hb.trade.api.routine.util.OfficeUtil;
import com.hb.trade.api.routine.util.ReviewItemExcelUtil;
import com.hb.trade.client.center.DictionaryClient;
import com.hb.trade.client.project.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.file.entity.UploadEntity;
import org.fzzn.core.file.service.PersistenceService;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.MsgUtil;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 招标文件评审项相关
 *
 * @author tian
 * @date 2022-4-13 10:33
 */
@Slf4j
@Version(1.0)
@Api(tags = {"招标文件评审项相关"})
@RequestMapping("/{version}")
@RestController
public class ApiReviewItemController {

    protected final ReviewItemClient reviewItemClient;
    protected final SectionClient sectionClient;
    protected final PersistenceService persistenceService;
    protected final ProjectClient projectClient;
    protected final EvaluationCommitteeClient evaluationCommitteeClient;
    protected final BidOpeningClient bidOpeningClient;
    protected final EvaluationClient evaluationClient;
    protected final DictionaryClient dictionaryClient;

    public ApiReviewItemController(ReviewItemClient reviewItemClient,
                                   SectionClient sectionClient,
                                   PersistenceService persistenceService,
                                   ProjectClient projectClient,
                                   EvaluationCommitteeClient evaluationCommitteeClient,
                                   BidOpeningClient bidOpeningClient,
                                   EvaluationClient evaluationClient,
                                   DictionaryClient dictionaryClient) {
        this.reviewItemClient = reviewItemClient;
        this.sectionClient = sectionClient;
        this.persistenceService = persistenceService;
        this.projectClient = projectClient;
        this.evaluationCommitteeClient = evaluationCommitteeClient;
        this.bidOpeningClient = bidOpeningClient;
        this.evaluationClient = evaluationClient;
        this.dictionaryClient = dictionaryClient;
    }

    /**
     * 查询评审项详情
     *
     * @param reviewItemFirstDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "查询评审项详情", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileId", value = "招标文件id", dataTypeClass = Long.class, required = true)
    })
    @PostMapping("/reviewItem/selectReviewItem")
    public ResponseDto selectReviewItem(@RequestBody ReviewItemFirstDto reviewItemFirstDto) {
        if (null == reviewItemFirstDto.getFileId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        reviewItemFirstDto.setCreateId(ShiroUtil.getUserId());
        reviewItemFirstDto.setCreateName(ShiroUtil.getUser().getFullName());
        return ResultUtil.msg(reviewItemClient.selectReviewItem(reviewItemFirstDto));
    }

    /**
     * 编辑一级评审项
     *
     * @param reviewItemFirstDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "编辑一级评审项", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileId", value = "招标文件id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "firstReviewItemTypeList", value = "组装的一级评审项集合", dataTypeClass = List.class, required = true)
    })
    @PostMapping("/reviewItem/editReviewItem")
    public ResponseDto editReviewItem(@RequestBody ReviewItemFirstDto reviewItemFirstDto) {
        if (null == reviewItemFirstDto.getFirstReviewItemTypeList() || null == reviewItemFirstDto.getFileId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        reviewItemFirstDto.setCreateId(ShiroUtil.getUserId());
        reviewItemFirstDto.setCreateName(ShiroUtil.getUser().getFullName());
        return ResultUtil.msg(reviewItemClient.editReviewItem(reviewItemFirstDto));
    }


    /**
     * 查询二级评审项列表
     *
     * @param reviewItemSecondDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "查询二级评审项列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "firstReviewItemId", value = "一级评审项id", dataTypeClass = Long.class, required = true),
    })
    @PostMapping("/reviewItem/selectReviewItemSecondList")
    public ResponseDto selectReviewItemSecondList(@RequestBody ReviewItemSecondDto reviewItemSecondDto) {
        if (null == reviewItemSecondDto.getFirstReviewItemId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        return ResultUtil.msg(reviewItemClient.selectReviewItemSecondList(reviewItemSecondDto));
    }


    /**
     * 保存，编辑二级评审项
     *
     * @param reviewItemSecondDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "保存，编辑二级评审项", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "二级评审项id", dataTypeClass = Long.class, required = false),
            @ApiImplicitParam(name = "fileId", value = "招标文件id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "firstReviewItemId", value = "一级评审项id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "secondReviewItemName", value = "评审项目名称", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "sort", value = "排序", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "reviewMode", value = "评审方式（1，定量，2，定性）", dataTypeClass = Integer.class, required = true),
            @ApiImplicitParam(name = "scoreRange", value = "打分范围（例：不低于10%，只存数字）", dataTypeClass = String.class),
            @ApiImplicitParam(name = "scoreTotalCondition", value = "评分汇总条件 1：直接平均  2：去掉最高最低再计算平均值", dataTypeClass = Integer.class),
    })
    @PostMapping("/reviewItem/editReviewItemSecond")
    public ResponseDto<ReviewItemSecondDto> editReviewItemSecond(@RequestBody ReviewItemSecondDto reviewItemSecondDto) {
        reviewItemSecondDto.setCreateId(ShiroUtil.getUserId());
        reviewItemSecondDto.setCreateName(ShiroUtil.getUser().getFullName());
        Message<Long> message = reviewItemClient.editReviewItemSecond(reviewItemSecondDto);
        if (message.isSuccess()) {
            reviewItemSecondDto.setId(message.getData());
            return ResultUtil.msg(MsgUtil.msg(reviewItemSecondDto));
        } else {
            return ResultUtil.fail(message.getMessage());
        }
    }


    /**
     * 删除二级评审项
     *
     * @param reviewItemSecondDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "删除二级评审项", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "二级评审项id", dataTypeClass = Long.class, required = true),
    })
    @PostMapping("/reviewItem/deleteReviewItemSecond")
    public ResponseDto deleteReviewItemSecond(@RequestBody ReviewItemSecondDto reviewItemSecondDto) {
        if (null == reviewItemSecondDto.getId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        return ResultUtil.msg(reviewItemClient.deleteReviewItemSecond(reviewItemSecondDto));
    }


    /**
     * 查询三级评审项列表
     *
     * @param reviewItemThirdDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "查询三级评审项列表", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "firstReviewItemId", value = "一级评审项id", dataTypeClass = Long.class, required = true),
    })
    @PostMapping("/reviewItem/selectReviewItemThirdList")
    public ResponseDto selectReviewItemThirdList(@RequestBody ReviewItemThirdDto reviewItemThirdDto) {
        if (null == reviewItemThirdDto.getFirstReviewItemId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        return ResultUtil.msg(reviewItemClient.selectReviewItemThirdList(reviewItemThirdDto));
    }


    /**
     * 保存，编辑三级评审项
     *
     * @param reviewItemThirdDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "保存，编辑三级评审项", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "二级评审项id", dataTypeClass = Long.class, required = false),
            @ApiImplicitParam(name = "fileId", value = "招标文件id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "firstReviewItemId", value = "一级评审项id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "secondReviewItemId", value = "二级评审项id", dataTypeClass = Long.class, required = true),
            @ApiImplicitParam(name = "thirdReviewItemName", value = "三级评审项名称", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "assessStandard", value = "评审标准", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "assessScore", value = "分值(数字)", dataTypeClass = String.class),
            @ApiImplicitParam(name = "sort", value = "排序", dataTypeClass = Integer.class, required = true),
    })
    @PostMapping("/reviewItem/editReviewItemThird")
    public ResponseDto editReviewItemThird(@RequestBody ReviewItemThirdDto reviewItemThirdDto) {
        reviewItemThirdDto.setCreateId(ShiroUtil.getUserId());
        reviewItemThirdDto.setCreateName(ShiroUtil.getUser().getFullName());
        return ResultUtil.msg(reviewItemClient.editReviewItemThird(reviewItemThirdDto));
    }


    /**
     * 删除三级评审项
     *
     * @param reviewItemThirdDto
     * @return org.fzzn.core.model.msg.ResponseDto
     * @author tian
     * @date 2022-4-13 14:03
     */
    @ApiOperation(value = "删除三级评审项", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "三级评审项id", dataTypeClass = Long.class, required = true),
    })
    @PostMapping("/reviewItem/deleteReviewItemThird")
    public ResponseDto deleteReviewItemThird(@RequestBody ReviewItemThirdDto reviewItemThirdDto) {
        if (null == reviewItemThirdDto.getId()) {
            return ResultUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        return ResultUtil.msg(reviewItemClient.deleteReviewItemThird(reviewItemThirdDto));
    }

     /**
      *
      * @Description:表格生成
      * @Author: zhongdl
      * @Date:2022/4/19 15:18
      * @param reviewEvaluationGenerateFormDTO:
      * @return: {@link ResponseDto }
      **/
    @ApiOperation(value = "表格生成(无生成记录先生成记录)", httpMethod = "POST")
    @PostMapping("/reviewEvaluationForm/generate")
    public ResponseDto generate(@RequestBody ReviewEvaluationGenerateFormDTO reviewEvaluationGenerateFormDTO) {
        Message<List<ReviewEvaluationFormDTO>> reviewEvaluationGenerateFormDTOMessage = reviewItemClient.generate(reviewEvaluationGenerateFormDTO);
        List<ReviewEvaluationFormDTO> reviewEvaluationForm = reviewEvaluationGenerateFormDTOMessage.getData();
        if (CollUtil.isEmpty(reviewEvaluationForm)){
            return ResultUtil.msg(reviewEvaluationGenerateFormDTOMessage);
        }
        //查询生成的表格的状态
        EvaluationSummaryAddDTO evaluationSummary = new EvaluationSummaryAddDTO();
        evaluationSummary.setSectionId(reviewEvaluationGenerateFormDTO.getSectionId());
        Message<EvaluationSummaryDTO> evaluationSummaryDTOMessage = evaluationClient.evaluationSummaryDetails(evaluationSummary);
        if (evaluationSummaryDTOMessage.getData() != null  && StrUtil.isNotEmpty(evaluationSummaryDTOMessage.getData().getSheetUrl())){
            return ResultUtil.msg(reviewEvaluationGenerateFormDTOMessage);
        }
        //合成评标报告

         String url = ReviewItemExcelUtil.mergExcel(reviewEvaluationForm,   reviewEvaluationGenerateFormDTO.getSectionId());
         if (StrUtil.isNotEmpty(url)){
             evaluationSummary.setSheetUrl(url);
             evaluationClient.updateEvaluationSummaryStatus(evaluationSummary);
         }
        return ResultUtil.msg(reviewEvaluationGenerateFormDTOMessage);
    }


    /**
      *
      * @Description:生成初级评审项excel
      * @Author: zhongdl
      * @Date:2022/4/19 15:18
      * @param reviewEvaluationGenerateFormDTO:
      * @return: {@link ResponseDto }
      **/
    @ApiOperation(value = "初步评审", httpMethod = "POST")
    @PostMapping("/reviewEvaluationForm/preliminary")
    public ResponseDto preliminary(@RequestBody ReviewEvaluationGenerateFormDTO reviewEvaluationGenerateFormDTO) {
        Message<List<ReviewItemSecondDto>> preliminaryMsg = reviewItemClient.preliminary( reviewEvaluationGenerateFormDTO.getSectionId());
        if (preliminaryMsg.isFail()){
            return ResultUtil.fail(preliminaryMsg.getMessage());
        }
        List<ReviewItemSecondDto> data = preliminaryMsg.getData();

        for (ReviewItemSecondDto reviewItemSecondDto : data) {
            String url = ReviewItemExcelUtil.preliminaryExcel(reviewItemSecondDto);
            //更新评标表格状态
              //评标表格id
            Long evaluationFormId = reviewItemSecondDto.getEvaluationFormId();
            if (evaluationFormId == null){
                continue;
            }
            updateReviewEvaluationForm(evaluationFormId,LogicEnum.YES.getCode(), url);


        }
        return ResultUtil.SUCCESS;
    }
     /**
      *
      * @Description:生成详细评审的Excel
      * @Author: zhongdl
      * @Date:2022/4/20 17:56
      * @param reviewEvaluationGenerateFormDTO:
      * @return: {@link ResponseDto }
      **/
    @ApiOperation(value = "详细评审", httpMethod = "POST")
    @PostMapping("/reviewEvaluationForm/detailed")
    public ResponseDto detailed(@RequestBody ReviewEvaluationGenerateFormDTO reviewEvaluationGenerateFormDTO) {
        Message<List<ReviewItemSecondDto>> detailedPersonalMsg = reviewItemClient.detailedPersonal( reviewEvaluationGenerateFormDTO.getSectionId());
        if (detailedPersonalMsg.isFail()){
            return ResultUtil.fail(detailedPersonalMsg.getMessage());
        }
        List<ReviewItemSecondDto> data = detailedPersonalMsg.getData();
        //详细评审个人
        for (ReviewItemSecondDto reviewItemSecondDto : data) {
            String url = ReviewItemExcelUtil.detailedPersonalExcel(reviewItemSecondDto);
            //更新评标表格状态
              //评标表格id
            Long evaluationFormId = reviewItemSecondDto.getEvaluationFormId();
            if (evaluationFormId == null){
                continue;
            }
            updateReviewEvaluationForm(evaluationFormId,LogicEnum.YES.getCode(), url);

        }
        Message<List<EvaluationCommitteeMembers>> members = evaluationCommitteeClient.listMembersBySectionId(reviewEvaluationGenerateFormDTO.getSectionId());

        //详细评审汇总
        Message<List<ReviewItemSecondDto>> summaryMsg = reviewItemClient.detailedPersonalSummary(reviewEvaluationGenerateFormDTO.getSectionId());
        if (summaryMsg.isFail()){
            return ResultUtil.fail(summaryMsg.getMessage());
        }
        List<ReviewItemSecondDto> summaryData = summaryMsg.getData();
        //详细评审汇总
        for (ReviewItemSecondDto reviewItemSecondDto : summaryData) {
            String url = ReviewItemExcelUtil.detailedSummary(reviewItemSecondDto,members.getData());
            //更新评标表格状态
            //评标表格id
            Long evaluationFormId = reviewItemSecondDto.getEvaluationFormId();
            if (evaluationFormId == null){
                continue;
            }
            updateReviewEvaluationForm(evaluationFormId,LogicEnum.YES.getCode(), url);


        }

        Message<ScoreSummaryExcelDTO> scoreSummary = reviewItemClient.scoreSummary(reviewEvaluationGenerateFormDTO.getSectionId());
        ScoreSummaryExcelDTO scoreSummaryExcelDTO = scoreSummary.getData();
        //生成评分汇总
        String url = ReviewItemExcelUtil.scoreSummary(scoreSummaryExcelDTO,members.getData());
        updateReviewEvaluationForm(scoreSummaryExcelDTO.getEvaluationFormSummaryId(),LogicEnum.YES.getCode(), url);
        //生成评分结论
        Message<AbstractProject> abstractProjectMessage = projectClient.detailBySectionId(reviewEvaluationGenerateFormDTO.getSectionId());
        String tendereeName = "招标人名称";
        if (abstractProjectMessage.getData() != null){
            AbstractProject project = abstractProjectMessage.getData();
            tendereeName = project.getAgencyOrganizeInfo().getName();
        }
        String conclusionUrl = ReviewItemExcelUtil.scoreConclusion(scoreSummaryExcelDTO,tendereeName,members.getData());
        updateReviewEvaluationForm(scoreSummaryExcelDTO.getEvaluationFormConclusionId(),LogicEnum.YES.getCode(), conclusionUrl);


        return ResultUtil.SUCCESS;
    }


    @ApiOperation(value = "报价评审", httpMethod = "POST")
    @PostMapping("/reviewEvaluationForm/quotationReview")
    public ResponseDto quotationReview(@RequestBody ReviewEvaluationGenerateFormDTO reviewEvaluationGenerateFormDTO) {
        Message<List<QuotationReviewExcelDTO>> quotationReviewMsg = reviewItemClient.quotationReview(reviewEvaluationGenerateFormDTO.getSectionId());
        if (quotationReviewMsg.isFail()){
            return ResultUtil.fail(quotationReviewMsg.getMessage());
        }
        BidSectionDTO bidSectionDTO = new BidSectionDTO();
        bidSectionDTO.setSectionId(reviewEvaluationGenerateFormDTO.getSectionId());
        Message<BidSectionDTO> bidSectionMsg = sectionClient.getBidSection(bidSectionDTO);
        if (bidSectionMsg.isFail() || bidSectionMsg.getData() == null){
            return ResultUtil.fail("标段数据不存在");
        }
        BidSectionDTO bidSection = bidSectionMsg.getData();
        List<QuotationReviewExcelDTO> data = quotationReviewMsg.getData();

        //详细评审个人
        String url = ReviewItemExcelUtil.quotationReviewExcel(data,bidSection);
        if(CollUtil.isEmpty(data)){
            return ResultUtil.SUCCESS;
        }
        updateReviewEvaluationForm(data.get(0).getEvaluationFormId(),LogicEnum.YES.getCode(),url);



        return ResultUtil.SUCCESS;
    }

    @ApiOperation(value = "评标报告", httpMethod = "POST")
    @PostMapping("/reviewEvaluationForm/reportBid")
    public ResponseDto reportBid(@RequestBody ReviewEvaluationGenerateFormDTO reviewEvaluationGenerateFormDTO) throws IOException {
        Map<String, String> paramMap = MapUtil.newHashMap();
        Long sectionId = reviewEvaluationGenerateFormDTO.getSectionId();
        BidSectionDTO bidSectionDTO = new BidSectionDTO();
        bidSectionDTO.setSectionId(sectionId);
        Message<BidSectionDTO> bidSectionMsg = sectionClient.getBidSection(bidSectionDTO);
        Message<AbstractProject> abstractProjectMessage = projectClient.detailBySectionId(sectionId);

        if (bidSectionMsg.isFail() || bidSectionMsg.getData() == null){
            return ResultUtil.fail("标段数据不存在");
        }
        if (abstractProjectMessage.isFail() || abstractProjectMessage.getData() == null){
            return ResultUtil.fail("项目信息不存在");
        }
        //2022-04-21 17:55
        AbstractProject abstractProject = abstractProjectMessage.getData();

        DistrictInfo areaInfo = StrUtil.isEmpty(abstractProject.getArea()) ? new DistrictInfo() : dictionaryClient.districtsById(abstractProject.getArea());
        DistrictInfo cityInfo = StrUtil.isEmpty(abstractProject.getCity()) ? new DistrictInfo() : dictionaryClient.districtsById(abstractProject.getCity());
        DistrictInfo provinceInfo = dictionaryClient.districtsById(abstractProject.getProvince());
        String date = DateUtil.format(bidSectionDTO.getOpenBidTime() == null ? LocalDateTime.now() : bidSectionDTO.getOpenBidTime(), "yyyy年MM月dd日 HH时mm分");

        BidSectionDTO bidSection = bidSectionMsg.getData();
        OpeningSetDTO openingSetDTO = new OpeningSetDTO();
        openingSetDTO.setId(bidSection.getId());
        Message<OpeningSetDTO> detail = bidOpeningClient.detail(openingSetDTO);
        openingSetDTO = detail.getData() == null ? openingSetDTO : detail.getData();
        //查询专家列表
        Message<List<EvaluationCommitteeMembers>> memberMsg = evaluationCommitteeClient.listMembersBySectionId(sectionId);
        List<EvaluationCommitteeMembers> membersList = CollUtil.isEmpty(memberMsg.getData()) ? CollUtil.list(false) : memberMsg.getData();

        //查询开标设置
         //公司名称
        paramMap.put("orgName",abstractProject.getBiddingOrganizeInfo().getName());
        //项目名称
        paramMap.put("projectName",bidSection.getProjectName());
        //项目编号
        paramMap.put("projectCode",bidSection.getProjectCode());
        //标段编号
        paramMap.put("sectionName",bidSection.getSectionName());
        //招标类型
        paramMap.put("commonTypeName", Enums.equals(CommonTypeEnum.OPEN,abstractProject.getCommonType()) ? "公开招标" : "邀请招标");
         //开标时间
        paramMap.put("openBidTime", date);
         //主持人
        paramMap.put("hostName", StrUtil.isEmpty(openingSetDTO.getHostName()) ? "/" : openingSetDTO.getHostName());
        //代理机构
        paramMap.put("agencyName", abstractProject.getAgencyOrganizeInfo().getName());
        //当前时间
        paramMap.put("dateTime",DateUtil.format(new Date(),new SimpleDateFormat("yyyy年MM月dd日")));
        //地点
        paramMap.put("placeName",provinceInfo.getDisName() + (StrUtil.isEmpty(cityInfo.getDisName()) ? "" : cityInfo.getDisName()) + (StrUtil.isEmpty(areaInfo.getDisName()) ? "" : areaInfo.getDisName()));
        //地点
        paramMap.put("contact",abstractProject.getAgencyOrganizeInfo().getContact());

        //查询投标人和投标报价
        BidSectionTenderDTO bidSectionTender = new BidSectionTenderDTO();
        bidSectionTender.setStatus(1);
        bidSectionTender.setSectionId(sectionId);
        Message<List<BidSectionTenderDTO>> listBidSectionTenderMsg = sectionClient.listBidSectionTender(bidSectionTender);
        List<BidSectionTenderDTO> listBidSectionTender = listBidSectionTenderMsg.getData();
        //组长名称
        List<EvaluationCommitteeMembers> evaluationCommitteeMembersList = membersList.stream().filter(members -> Enums.equals(LogicEnum.YES, members.getChairmanFlag())).collect(Collectors.toList());
        paramMap.put("leaderName",CollUtil.isEmpty(evaluationCommitteeMembersList) ? "" : evaluationCommitteeMembersList.get(0).getMemberName());
        //招标人代表
        List<String> bidRepresentativeList = membersList.stream().filter(members -> Enums.equals(MemberTypeEnum.BID_INVITER, members.getMemberType())).map(EvaluationCommitteeMembers::getMemberName).collect(Collectors.toList());
        paramMap.put("bidRepresentativeNumber",CollUtil.size(bidRepresentativeList) + "");
        //招标人代表
        paramMap.put("bidRepresentativeName",CollUtil.isEmpty(bidRepresentativeList) ? "-" : CollUtil.join(bidRepresentativeList,","));

        //专家人数
        paramMap.put("representativeNumber",(membersList.size() - CollUtil.size(bidRepresentativeList)) + "");

        //查询投标企业
        Message<ScoreSummaryExcelDTO> scoreSummary = reviewItemClient.scoreSummary(reviewEvaluationGenerateFormDTO.getSectionId());
        ScoreSummaryExcelDTO scoreSummaryExcelDTO = scoreSummary.getData();
        if (scoreSummaryExcelDTO == null){
            scoreSummaryExcelDTO = new ScoreSummaryExcelDTO();
        }
        List<ScoreSummarySecondDTO> orgList = CollUtil.isEmpty(scoreSummaryExcelDTO.getOrgList()) ? CollUtil.list(false) : scoreSummaryExcelDTO.getOrgList();
        for (ScoreSummarySecondDTO scoreSummarySecondDTO : orgList) {
            List<ReviewItemSecondDto> reviewItemSecondDtos = scoreSummarySecondDTO.getReviewItemSecondDtos();
            if (CollUtil.isEmpty(reviewItemSecondDtos)){
                scoreSummarySecondDTO.setFinalScore(0.0);
            }
            Double reduce = reviewItemSecondDtos.stream().map(ReviewItemSecondDto::getFinalScore).reduce(0.0, (a, b) -> a + b);

            BigDecimal bigDecimal = new BigDecimal(reduce).setScale(2, RoundingMode.HALF_UP);
            scoreSummarySecondDTO.setFinalScore(bigDecimal.doubleValue());

        }

        //设置评委会成员表格数据
        int membersListSize = membersList.size();
        String[][] membersDataArr = new String[membersListSize][];
        for (int i = 0; i < membersListSize; i++) {
            EvaluationCommitteeMembers committeeMembers = membersList.get(i);
            String[] dataArr = new String[]{committeeMembers.getMemberName(),committeeMembers.getMemberCompany(),committeeMembers.getMajor()};
            membersDataArr[i] = dataArr;
        }
        if (CollUtil.isEmpty(listBidSectionTender)){
            listBidSectionTender = CollUtil.list(false);
        }
        listBidSectionTender = listBidSectionTender.stream().filter(item -> StrUtil.isNotEmpty(item.getDecryptContent())).collect(Collectors.toList());
        int size = CollUtil.size(listBidSectionTender);

        //设置投标企业名称
        String[][] bidOrgNameDataArr = new String[size][];
        for (int i = 0; i < size; i++) {
            BidSectionTenderDTO bidSectionTenderDTO = listBidSectionTender.get(i);
            String[] bidOrgNameData = {(i + 1) + "", bidSectionTenderDTO.getOrgName()};
            bidOrgNameDataArr[i] = bidOrgNameData;
        }

        //设置开标一览表数据
        String[][] openingScheduleDataArr = new String[listBidSectionTender.size() + 1][];
        //设置开标一览表表头
        for (int i = 0; i < size; i++) {
            BidSectionTenderDTO bidSectionTenderDTO = listBidSectionTender.get(i);
            //如果解密失败或解密内容为空
            if (StrUtil.isEmpty(bidSectionTenderDTO.getDecryptContent())){
                continue;
            }
            JSONObject jsonObject = JSONUtil.parseObj(bidSectionTenderDTO.getDecryptContent(), false, true);
            int j = 1;
            String[] headData = new String[jsonObject.keySet().size() + 1];
            headData[0] = "序号";
            for (String key : jsonObject.keySet()) {
                headData[j] = key;
                j++;
            }
            openingScheduleDataArr[0] = headData;
            break;
        }
        String[] headData = openingScheduleDataArr[0];
        int length = headData.length;
        for (int i = 0; i < size; i++) {
            BidSectionTenderDTO bidSectionTenderDTO = listBidSectionTender.get(i);
            JSONObject jsonObject = JSONUtil.parseObj(bidSectionTenderDTO.getDecryptContent(), false, true);
            String[] openingScheduleData = new String[length];
            openingScheduleData[0] = i + 1 + "";
            for (int j = 1; j < length; j++) {
                openingScheduleData[j] = StrUtil.isEmpty(jsonObject.get(headData[j],String.class)) ? "" : jsonObject.get(headData[j],String.class);
            }
            openingScheduleDataArr[i + 1] = openingScheduleData;
        }
        //设置评标结果数据
        List<ScoreSummarySecondDTO> orgOderList = orgList.stream().sorted(Comparator.comparing(ScoreSummarySecondDTO::getFinalScore).reversed()).collect(Collectors.toList());
        int orgOderListSize = orgOderList.size();
        String[][] evaluationResultDataArr = new String[orgOderListSize][];

        for (int i = 0; i < orgOderListSize; i++) {
            int j = i + 1;
            ScoreSummarySecondDTO scoreSummarySecondDTO = orgOderList.get(i);
            String[] openingScheduleData = {j + "", scoreSummarySecondDTO.getOrgName(),scoreSummarySecondDTO.getQuotedPrice(),scoreSummarySecondDTO.getFinalScore() + "",j + ""};
            evaluationResultDataArr[i] = openingScheduleData;
            //摄者中标候选人
            if(i < 3){
                paramMap.put("candidateOrgName" + j,scoreSummarySecondDTO.getOrgName());
            }
        }
        for (int i = 1; i < 4; i++) {
            if (StrUtil.isEmpty(paramMap.get("candidateOrgName" + i))){
                //防止中标候选人为空的问题
                paramMap.put("candidateOrgName" + i," ");
            }
        }
        //投标家数
        paramMap.put("bidsNumber",size + "");
        File upperBytesFile =  OfficeUtil.wordToWordBytesAddTable("template/pingbiaobaogaoupperpart.docx", paramMap,membersDataArr,bidOrgNameDataArr);
        File upperFile =  OfficeUtil.wordToWordBytesAddTable(upperBytesFile,openingScheduleDataArr);
        File lowwerBytesFile =  OfficeUtil.wordToWordBytesAddTable("template/pingbiaobaogaolowwerpart.docx", paramMap,evaluationResultDataArr);
        //移除水印
        File fileRemoveWate = OfficeUtil.removeSpireDocWater(upperFile);
        File lowwerFileRemoveWate = OfficeUtil.removeSpireDocWater(lowwerBytesFile);
        //合并word
        File pathFile = OfficeUtil.wordMerge(fileRemoveWate, lowwerFileRemoveWate);
        String url = persistenceService.updateToOss(new UploadEntity(), new FileInputStream(pathFile), FileUtil.getName(pathFile));
        log.info("评标报告的url:{}",url);

        //更新评标报告的生成状态
        EvaluationSummaryAddDTO evaluationSummaryAddDTO = new EvaluationSummaryAddDTO();
        evaluationSummaryAddDTO.setReportUrl(url);
        evaluationSummaryAddDTO.setSectionId(sectionId);
        Message<Boolean> booleanMessage = evaluationClient.updateEvaluationSummaryStatus(evaluationSummaryAddDTO);
        return ResultUtil.SUCCESS;
    }




    /**
     * @param evaluationFormId:表格id
     * @param status:状态
     * @param url:生成的url
     * @Description:更新excel生成表格的状态
     * @Author: zhongdl
     * @Date:2022/4/23 18:03

     **/
    private void updateReviewEvaluationForm(Long evaluationFormId, Integer status, String url) {
        ReviewEvaluationFormDTO reviewEvaluationFormDTO = new ReviewEvaluationFormDTO();
        reviewEvaluationFormDTO.setId(evaluationFormId);
        reviewEvaluationFormDTO.setStatus(LogicEnum.YES.getCode());
        reviewEvaluationFormDTO.setAnnexAddress(url);
        Message<Boolean> update = reviewItemClient.updateReviewEvaluationForm(reviewEvaluationFormDTO);
    }


}
